<?php
namespace App\Models\V5;
use DB;
use App\Models\V1\MemberModel;


class ChapterModel{

    private $chapterDb ;    //分会表
    private $prisidentDb;   //会长表
    private $perPage    = 20;

    public function __construct(){
        $this->chapterDb    = DB::table('chapter as a');
        $this->prisidentDb  = DB::table('chapter_prisident as b');
    }


    /*===========================================================
    ************************ 分会管理****************************
    =============================================================*/

    /**
     * 添加分会
     * */
    public function add_chapter($data){
        if(isset($data['chapter_id']) && $data['chapter_id'] > 0){
            $result = DB::table('chapter')->where('chapter_id',$data['chapter_id'])->update($data);
        }else{
            unset($data['chapter_id']);
            $data['is_delete']  = 0;
            $data['add_time']   = date_time();
            $data['surplus_money']  = $data['total_money']=0;
            $result = DB::table('chapter')->insert($data);
        }
        return $result;
    }


    /**
     * 获得分会列表信息
     * @param string $keywords 关键字
     * */
    public function get_chapters($keywords=''){

        $db = DB::table('chapter as a')
            ->leftJoin('chapter_prisident as b',function($query){
                $query->on('b.chapter_id','=','a.chapter_id')
                    ->where('b.prisident_type','=','Z')
                    ->where('b.is_delete','=',0);
            })
            ->leftJoin('memberinfo as m','m.UserID','=','b.user_id')
            ->where('a.is_delete',0)
            ->select('a.*','m.YourName');
        if($keywords){
            $db->where(function($db) use ($keywords)
            {
                $keywords = "%$keywords%";
                $db->where('a.chapter_name','like',$keywords)
                    ->orWhere('m.YourName','like',$keywords);
            });
        }
        $chapters = $db->paginate(10);

        return $chapters;
    }


    /**
     * 删除分会
     * @param integer $chapterId 分会ID
     * */
    public function delete_chapter($chapterId){
        DB::table('chapter')
            ->where('chapter_id',$chapterId)
            ->update(['is_delete'=>1]);
    }


    /**
     * 获取分会信息
     * */
    public function chapter_info($chapterId){
        $chapterInfo = DB::table('chapter')
            ->where('is_delete',0)
            ->where('chapter_id',$chapterId)
            ->first();

        return $chapterInfo;
    }


    /**
     * 获取一个空的分会对象
     * */
    public function get_empty_chapter(){
        $chapterInfo    = DB::table('chapter')->where('is_delete',0)->first();
        foreach($chapterInfo as $key => $v){
            if(gettype($v) == gettype(1)){
                $chapterInfo->$key = 0;
            }else{
                $chapterInfo->$key = "";
            }
        }
        return $chapterInfo;
    }



    /*===========================================================
     ************************ 会长管理 ***************************
     =============================================================*/

    /**
       * 统计会长数量
       *
       * @param number $chapterId
       * @param string $type  chapter's type F:副会长 Z:正会长
       * @param integer $cityId  区域   >0： 制定区域的 0： 所有的 <0:非该区域的
       * */
    public function count_prisident($chapterId,$type="",$cityId = 0){
        $DB = DB::table('chapter_prisident as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->where('a.chapter_id',$chapterId)
            ->where('a.is_delete',0);


        if($type){
            $DB->where('a.prisident_type',$type);
        }

        if($cityId > 0 ){
            $DB->where('b.city',$cityId);
        }elseif($cityId < 0){
            $cityId = abs($cityId);
            $DB->where('b.city','<>',$cityId);
        }
        return $DB->count();
    }


    /**
     * 添加会长
     * */
    public function add_prisident($prisidentInfo){

        if(isset($prisidentInfo['chapter_prisident_id'])){
            $prisidentId = $prisidentInfo['chapter_prisident_id'];
            $prisidentId = $prisidentId > 0 ? $prisidentId : 0;
        }else{
            $prisidentId = 0;
        }

        $prisidentInfo['release_time']  = date_time();
        if($prisidentId > 0){
            DB::table('chapter_prisident')
                ->where('chapter_prisident_id',$prisidentId)
                ->update($prisidentInfo);
        }else{
            $prisidentInfo['add_time']      = date_time();
            $prisidentInfo['surplus_money']  = $prisidentInfo['total_money'];
            DB::table('chapter_prisident')->insert($prisidentInfo);
        }
    }


    //是否存在某位会长
    public function exists_prisident($chapterId,$userId){

        $prisident = DB::table('chapter_prisident')
            ->where('chapter_id',$chapterId)
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->first();

        return $prisident ? true : false;
    }



    /**
     * 删除会长
     * @param integer $prisidentId 分会会长
     * */
    public function delete_prisident($prisidentId){

        DB::table('chapter_prisident')
            ->where('chapter_prisident_id',$prisidentId)
            ->update(['is_delete'=>1]);

    }



    /**
     * 获得分会会长列表
     * @param number $chapterId 分会ID
     * @param string $keywords 关键字
     * @param string $type 会长类型F:副会长 Z:正会长
     * @return Object
     * */
    public function get_chapter_prisidents($chapterId,$keywords = '',$type=""){
        $colums = [
            'a.chapter_prisident_id',
            'a.total_money',
            'a.surplus_money',
            'a.prisident_type',
            'a.add_time',
            'b.UserName',
            'b.YourName',
            'b.UserID'
        ];

        $prisidents = DB::table('chapter_prisident as a')
            ->leftJoin('memberinfo as b','b.UserId','a.user_id')
            ->select($colums)
            ->where('a.is_delete',0)
            ->where('a.chapter_id',$chapterId);
        if($keywords){
            $keywords = "%{$keywords}%";
            $prisidents->where(function($query) use ($keywords){
                $query->orWhere('b.UserName','like',$keywords)
                    ->orWhere('b.YourName','like',$keywords);
            });
        }

        if($type){
            $prisidents->where('a.prisident_type',$type);
        }
        $prisidents = $prisidents->paginate($this->perPage);

        $types  = ['Z'=>"发起人",'F'=>'会长'];
        foreach($prisidents as $prisident){
            $prisident->prisident_type_name = $types[$prisident->prisident_type];
        }
        $prisidents = $prisidents ? $prisidents : [];
        return $prisidents;
    }


    /**
     * 获得会长信息
     *
     * */
    public function get_prisident_info($prisidentId){

        $parisidentInfo = DB::table('chapter_prisident as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->where('a.chapter_prisident_id',$prisidentId)
            ->where('a.is_delete',0)
            ->first();

        return $parisidentInfo;
    }




    /**
     * 获得空的会长信息
     *
     * */
    public function get_empty_prisident(){
        $prisidentInfo = DB::table('chapter_prisident')
            ->first();

        foreach($prisidentInfo as $key => $v){
            if(gettype($v) == 'integer' || gettype($v) == 'double'){
                $prisidentInfo->$key = 0;
            }elseif(gettype($v) == 'string'){
                $prisidentInfo->$key = "";
            }
        }
        return $prisidentInfo;
    }


    /**
     * 获得分会发起人信息，原始会长
     * @param integer $chapterId 分会ID
     * @return Object
     * */
    public function get_chapter_prisident_info($chapterId){
        $prisidentINfo = DB::table('chapter_prisident as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->where('a.chapter_id',$chapterId)
            ->where('a.is_delete',0)
            ->where('a.prisident_type','Z')
            ->first();

        return $prisidentINfo;
    }


    /**
     * 检查用户是不是分会会长
     * @param integer $userId 用户ID
     * @return boolean
     * */
    public function get_prisident_by_userid($userId){
        $info = DB::table('chapter_prisident')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->first();
        $info = $info ? $info : false;
        return $info;
    }


    /**
     * 扣除会长的余额
     * @param integer $userId 用户ID
     * @param integer $money  扣除金额
     * */
    public function use_prisident_money($userId,$money){
        $res = DB::table('chapter_prisident')
            ->where('user_id',$userId)
            ->decrement('surplus_money',$money);
        return $res;
    }

    public function return_prisident_money($userId,$money){
        DB::table('chapter_prisident')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->increment("surplus_money",$money);
    }

    /**==========================================================
     ************************ 学习官  drp ********************
     *============================================================*/

    /**
     * 添加分会下的学习官
     * @param integer $chapterId 分会ID
     * @param integer $userId   用户ID
     * @param integer $money    用户金额
     * */
    public function add_chapter_officer($chapterId,$userId,$money){
        $data   = [
            'chapter_id'    => $chapterId,
            'user_id'       => $userId,
            'total_money'   => $money,
            'payed_money'   => $money,
            'surplus_money' => $money
        ];
        DB::table('chapter_drp')->insert($data);
    }

    /**
     * 统计分会下的学习官数量
     *
     * @param number $chapterId 分会ID
     * @param number $cityId    城市ID
     * @param number $userId    用户ID
     * @return number
     * */
    public function count_drp($chapterId,$cityId=0,$userId=0){
        $DB = DB::table('chapter_drp as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->where('a.chapter_id',$chapterId)
            ->where('a.is_delete',0)
            ->where('a.user_id',"<>",$userId);

        if($cityId > 0){
            $DB->where('b.city',$cityId);
        }elseif($cityId < 0){
            $cityId = abs($cityId);
            $DB->where('b.city','<>',$cityId);
        }
        $count = $DB->count();

        return $count;
    }


    public function get_chapter_clos($chapterId,$keywords = ''){

        $db = DB::table('chapter_drp as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            //->select('')
            ->where('a.is_delete',0)
            ->where('b.DeleteMark',1)
            ->where('a.chapter_id',$chapterId);
        if($keywords){
            $db->where(function($db) use ($keywords)
            {
                $keywords = "%$keywords%";
                $db->where('b.UserName','like',$keywords)
                    ->orWhere('b.YourName','like',$keywords);
            });
        }
        $clos = $db->paginate($this->perPage);
        return $clos;
    }


    /**
     * 统计本分会学习官发展的学习官
     * @param $chapterId integer 分会ID
     * @param $userId integer 用户ID
     * @param $cityId integer 城市ID
     * */
    public function count_chapter_clo_of_clo($userId,$cityId,$chapterId)
    {
        return $this->get_chapter_clo_of_clo($chapterId,$userId,'',$cityId,true);
    }


    /**
     * 获得分会下的学习官
     * @param $chapterId integer 分会ID
     * @param $userId   integer 学习官用户ID 如果>0 则仅获取指定学习官下面的学习官
     * @param $keywords string  关键字
     * @param $city integer 城市ID
     * @param $isCount boolean 是否是城市
     * @return any
     * */
    public function get_chapter_clo_of_clo($chapterId,$userId,$keywords='',$city=0,$isCount=false){
        $colums = [
            'a.chapter_drp_id',
            'a.total_money',
            'a.surplus_money',
            'a.add_time',
            'b.UserName',
            'b.YourName',
            'b.UserID'
        ];

        $isPrisident    = $this->isFaqiren($userId);
        $memberModel    = new MemberModel();
        $drpInfo        = $memberModel->get_member_drp_info($userId);
        $drpId          = $drpInfo->DRPID;

        $db = DB::table('chapter_drp as a')
            ->leftJoin('memberinfo as b','b.UserId','a.user_id')
            ->leftJoin('memberdrp as drp','drp.MemNumber','=','b.MemNumber')
            ->select($colums)
            ->where('a.is_delete',0)
            ->where('drp.DeleteMark',1)
            ->where('drp.DRPID',"<>",$drpId);


        if($isPrisident)
        {

            $db->where(function($db) use ($chapterId,$drpId){
                $db->where('drp.ParentID',$drpId)
                    ->orWhere('a.chapter_id',$chapterId);
            });
        }
        else
        {
            $db->Where(function($db) use ($chapterId,$drpId)
            {
                $db->where('drp.ParentID',$drpId)
                    ->orWhere(function($db) use ($chapterId,$drpId){
                        $drpId = "%$drpId%";
                        $db->where('drp.IDTree','like',$drpId)
                            ->where('a.chapter_id',$chapterId);
                    });
            });
        }

        if($city>0){
            $db->where('b.city','=',$city);
        }

        if($city < 0){
            $city = abs($city);
            $db->where('b.city','<>',$city);
        }

        if($keywords){
            $db->where(function($query) use ($keywords){
                $keywords = "%{$keywords}%";
                $query->orWhere('b.UserName','like',$keywords)
                    ->orWhere('b.YourName','like',$keywords);
            });
        }


        if($isCount){
            return $db->count();
        }

        $clos = $db->paginate($this->perPage);
        $prisidents = $clos ? $clos :[];
        return $prisidents;
    }


    /**
     * 获得分会学习官信息
     * @param integer $userId 用户ID
     * */
    public function get_chapter_officer_info($userId){
        $colums = [
            'a.chapter_drp_id',
            'a.total_money',
            'a.payed_money',
            'a.surplus_money',
            'a.add_time',
            'b.UserName',
            'b.YourName',
            'b.UserID'
        ];

        $chapterDrpInfo = DB::table('chapter_drp as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->select($colums)
            ->where('a.user_id',$userId)
            ->where('a.is_delete',0)
            ->first();
        return $chapterDrpInfo;
    }

    /**
     * 通过学习官ID获取信息
     *
     * */
    public function get_chapter_officer_info_by_officerid($officerId){
        $colums = [
            'a.chapter_drp_id',
            'a.chapter_id',
            'a.total_money',
            'a.payed_money',
            'a.surplus_money',
            'a.add_time',
            'b.UserName',
            'b.YourName',
            'b.UserID'
        ];

        $chapterDrpInfo = DB::table('chapter_drp as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->select($colums)
            ->where('a.chapter_drp_id',$officerId)
            ->where('a.is_delete',0)
            ->first();
        return $chapterDrpInfo;
    }

    /**
     * 扣除学习官的余额
     * @param integer $userId 用户ID
     * @param integer $money  扣除金额
     * */
    public function use_officer_money($userId,$money){
        $res = DB::table('chapter_drp')
            ->where('user_id',$userId)
            ->decrement('surplus_money',$money);
        return $res;
    }

    /**
     * 返回学习官的金额
     * @param integer $userId 用户ID
     * @param integer $money 用户的金额
     * */
    public function return_officer_money($userId,$money){
        DB::table('chapter_drp')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->increment("surplus_money",$money);
    }



    /**
     * 修改学习官信息
     * */
    public function update_officer_info($officerInfo){

        if(isset($officerInfo['chapter_drp_id'])){
            $officerId  = $officerInfo['chapter_drp_id'];
            unset($officerInfo['chapter_drp_id']);
            unset($officerInfo['user_id']);
            if($officerId > 0){
                return DB::table('chapter_drp')
                    ->where('chapter_drp_id',$officerId)
                    ->update($officerInfo);
            }
        }

        $officerInfo['add_time']        = date_time();
        $officerInfo['surplus_money']   = $officerInfo['total_money'];
        return DB::table('chapter_drp')
            ->insertGetId($officerInfo);
    }

    /**
     *删除学习官
     * */
    public function delete_officer(){

    }

    /**===========================================================
      ************************ 会员 相关********************
      *=============================================================*/

    /**
     * 添加分会会员
     * @param integer $chapterId 分会ID
     * @param integer $userId 会员ID
     * */
    public function add_chapter_member($chapterId,$userId){
        $data   = [
            'chapter_id'    => $chapterId,
            'user_id'       => $userId,
            'add_time'      => date_time()
        ];
        DB::table('chapter_member')->insert($data);
    }

    /**
     * 统计会员信息
     *
     * @param number $chapterId 分会ID
     * @param number $cityId 城市ID
     * */
    public function count_member($chapterId,$cityId){
        $DB = DB::table('chapter_member as a ')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->where('a.chapter_id',$chapterId)
            ->where('a.is_delete',0);
        if($cityId > 0){
            $DB->where('b.city',$cityId);
        }elseif($cityId < 0){
            $cityId = abs($cityId);
            $DB->where('b.city','<>',$cityId);
        }
        return $DB->count();
    }

    /**
     * 获得分会下的所有订单
     * @param $chapterId integer 分会ID
     * @param $keywords string 关键字
     *
     * @return Object
     * */
    public function get_chapter_members($chapterId,$keywords = ''){

        $db = DB::table('chapter_member as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->where('a.chapter_id',$chapterId)
            ->where('a.is_delete',0)
            ->where('b.DeleteMark',1);


        if($keywords){
            $keywords = "%$keywords%";
            $db->where(function($db) use ($keywords)
            {
                $db->where('b.UserName','like',$keywords)
                    ->orWhere('b.YourName','like',$keywords);
            });
        }
        $members = $db->paginate($this->perPage);
        return $members;
    }


    /**
     * 统计分会学习官的会员
     * @param integer $chapterId 分会ID
     * @param integer $userId 用户ID
     * @param integer $cityId 城市ID
     * @return integer
     * */
    public function count_chapter_member_of_clo($userId,$cityId,$chapterId){
        $count = $this->get_chapter_members_of_clo($chapterId,$userId,"",$cityId,true);
        return $count;
    }


    /**
     * 判断是否是发起人
     * */
    public function isFaqiren($userId){
        $isPrisident = DB::table('chapter_prisident')
            ->where('user_id',$userId)
            ->where('prisident_type','Z')
            ->where('is_delete',0)
            ->first();
        return $isPrisident ? true : false;
    }


    /**
     * 获得分会会员
     * @param number  $chapterId 分会ID
     * @param integer $userId 学习官用户ID
     * @param string  $keywords 查找关键字
     * @param integer $city 城市ID
     * @param boolean $isCount 是否统计
     * @return Object
     * */
    public function get_chapter_members_of_clo($chapterId,$userId,$keywords='',$city=0,$isCount = false){

        $memberModel = new MemberModel();
        $drpInfo     = $memberModel->get_member_drp_info($userId);
        $parentId    = $drpInfo->DRPID;

        $db = DB::table('chapter_member as a')
            ->leftJoin('memberinfo as b','b.UserID','=','a.user_id')
            ->leftJoin('memberdrp as drp','drp.MemNumber','=','b.MemNumber')
            ->select('b.UserID','b.UserName','b.YourName','a.add_time','a.chapter_user_id')
            ->where('a.is_delete',0)
            ->where('a.user_id',"<>",$userId)
            ->where('b.DeleteMark',1)
            ->where('drp.DeleteMark',1)
            ->where('drp.DRPLevel',2)
            ->where(function($query) use ($chapterId,$parentId){
                $query->where('a.chapter_id',$chapterId)
                    ->orWhere('drp.ParentID',$parentId);
            });

        //检查是不是会长
        $isPrisident = $this->isFaqiren($userId);
        if(!$isPrisident){
            $db->where('drp.IDTree','like',"%$parentId%");
        }


        if($city>0){
            $db->where('b.city','=',$city);
        }

        if($city < 0){
            $city = abs($city);
            $db->where('b.city','<>',$city);
        }

        if($keywords){
            $db->where(function($query) use ($keywords){
                $keywords = "%{$keywords}%";
                $query->orWhere('b.UserName','like',$keywords)
                    ->orWhere('b.YourName','like',$keywords);
            });
        }


        if($isCount){
            return $db->count();
        }

        $members = $db->paginate($this->perPage);
        $members = $members ? $members :[];
        return $members;
    }



    /**===========================================================
      ************************ 企业 ********************
      *=============================================================*/

    /**
     * 添加分会下的公司
     * @param integer $chapterId 分会ID
     * @param integer $companyId 公司ID
     *
     * */
    public function add_chapter_company($chapterId,$companyId){
        $data = [
            'chapter_id'    => $chapterId,
            'company_id'    => $companyId,
            'add_time'      => date_time()
        ];
        DB::table('chapter_company')->insert($data);
    }


    /**
     * 统计分会下的公司
     *
     * @param number $chapterId 分会ID
     * */
    public function count_company($chapterId){
        return DB::table('chapter_company')
            ->where('chapter_id',$chapterId)
            ->where('is_delete',0)
            ->count();
    }


    public function get_chapter_companys($chapterId,$keywords = ''){

        $colums = [
            'a.chapter_company_id',
            'a.add_time',
            'b.company_name',
            'b.vip_port',
            'b.company_id',
            'd.YourName'
        ];

        $db = DB::table('chapter_company as a')
            ->leftJoin('company as b','b.company_id','=','a.company_id')
            ->leftJoin('memberinfo as d','d.UserID','=','b.drp_user_id')
            ->select($colums)
            ->where('a.is_delete',0)
            ->where('a.chapter_id',$chapterId);
        if($keywords){
            $db->where('b.company_name','like',"%$keywords%");
        }

        $companys = $db->paginate($this->perPage);
        return $companys;
    }

    /**
     * 统计分会下学习官开发的企业会员
     * @param $chapterId integer 分会ID
     * @param $userId integer 用户ID
     * @return integer
     * */
    public function count_chapter_company_of_clo($userId,$chapterId=0){

        return $this->get_chapter_companys_of_clo($chapterId,$userId,"",0,true);

    }


    /**
     * 获取分会下的公司列表
     * @param $chapterId inteter 分会ID
     * @param $userId integer 用户ID
     * @param $keywords string 关键字
     * @param $city integer 城市ID
     * @param $isCount boolean 是否是统计
     * @return Object
     * */
    public function get_chapter_companys_of_clo($chapterId,$userId,$keywords='',$city=0,$isCount = false){
        $colums = [
            'a.chapter_company_id',
            'a.add_time',
            'b.company_name',
            'b.vip_port',
            'b.company_id',
        ];

        $db = DB::table('chapter_company as a')
            ->leftJoin('company as b','b.company_id','a.company_id')
            ->select($colums)
            ->where('a.is_delete',0)
            ->where('a.chapter_id',$chapterId);

        $isPrisident = $this->isFaqiren($userId);
        if($isPrisident){ //本分会所有的 以及自己开发的其他分会的
            $db->where(function($db) use ($chapterId,$userId){
                 $db->where('a.chapter_id',$chapterId)
                     ->orWhere('b.drp_user_id',$userId);
            });
        }else{
            $db->where('b.drp_user_id',$userId);
        }

        if($city>0){
            $db->where('b.city','=',$city);
        }

        if($city < 0){
            $city = abs($city);
            $db->where('b.city','<>',$city);
        }


        if($keywords)
        {
            $keywords = "%{$keywords}%";
            $db->where('b.company_name','like',$keywords);
        }


        if($isCount){
            return $db->count();
        }
        $companys = $db->paginate($this->perPage);

        $companys = $companys ? $companys :[];
        return $companys;
    }



    /**
     * 获得用户角色
     * @param number $userId 用户ID
     * @return array
     * */
    public function get_user_role($userId){

        static $_MEMBER_    = 1;//普通会员
        static $_OFFICER_   = 2;//学习官
        static $_VICE_PRI   = 3;//会长
        static $_PRI_       = 4;//发起人


        //检查用户属于哪个分会
        $info = DB::table('chapter_prisident')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->first();


        //1.检查是不是正会长|副会长
        if($info){
            if($info->prisident_type == 'F'){
                $role   = $_VICE_PRI;
            }else{
                $role   = $_PRI_;
            }
            $info->role = $role;
            return $info;
        }

        //2.检查是不是学习官
        $info = DB::table('chapter_drp')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->first();
        if($info){
            $info->role = $_OFFICER_;
            return $info;
        }


        //如果都不是 禁止进入系统
        $info = DB::table('chapter_member')
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->select('chapter_id')
            ->first();

        if($info){
            $info->role = $_MEMBER_;
            return $info;
        }
        $obj = new \stdClass();
        $obj->role      = 0;
        $obj->chapterId = 0;
        return $obj;
    }


    /**
     * 获得分会下的订单 订单是要根据权限来查询的  1.需要审核的人  2.提交订单的人
     * 登录者能看的订单并不仅仅限于本分会，其他分会也有可能
     * @param integer $chapterId 分会ID
     * @param integer $userId 用户ID
     * @param integer $orderStatus 订单状态 0：总部未审核 1.总部审核通过 2.总部审核未通过
     * @param string  $keywords 订单状态
     * */
    public function get_chapter_orders($chapterId=0,$userId=0,$orderStatus=-1,$keywords= ''){


        $db = DB::table('chapter_order as a')
                    ->leftJoin('chapter as b','b.chapter_id','=','a.chapter_id')
                    ->leftJoin('memberinfo as m ','m.UserID','=','a.user_id')
                    ->select('a.*','b.chapter_name','m.YourName')
                    ->where(function($query) use ($userId){
                        $query->where('a.user_id',$userId)
                        ->orWhere('a.check_user_id',$userId)
                        ->orWhereRaw("FIND_IN_SET($userId,a.income_member)");
                    });

        if($orderStatus == 0){
            $db->where('a.company_check_status',$orderStatus);
        }elseif($orderStatus > 0){
            $db->where('a.company_check_status','>',0);
        }

        if($keywords != ''){
            $db->where(function($query) use ($keywords){
                $keywords = "%{$keywords}%";
                $query->orWhere('a.new_member_name','like',$keywords)
                    ->orWhere('a.new_member_mobile','like',$keywords)
                    ->orWhere('a.new_company_name','like',$keywords)
                    ->orWhere('a.new_company_code','like',$keywords);
            });
        }

        $orders = $db->orderBy('a.chapter_order_id','desc')->paginate(9);

        $memberTypes    = ['company'=>'企业','member'=>'个人','clo'=>'学习官'];
        foreach($orders as $order){
            $order->memberTypeName = $memberTypes[$order->order_type];
        }
        return $orders;
    }


    /**
     * 获得分会所有订单
     * @param $chapterId integer 分会ID
     * @param $orderStatus integer 订单状态
     * @param $keywords string 查询关键字
     * */
    public function get_all_chapter_orders($chapterId=0,$orderStatus = -1,$keywords = ''){

        $db = DB::table('chapter_order as a')
            ->leftJoin('chapter as b','b.chapter_id','=','a.chapter_id')
            ->leftJoin('memberinfo as m ','m.UserID','=','a.user_id')
            ->select('a.*','b.chapter_name','m.YourName');

        if($chapterId > 0)
        {
            $db->where('a.chapter_id',$chapterId);
        }

        if($orderStatus == 0)   //未审核的订单
        {
            $db->where('a.company_check_status',$orderStatus);
        }
        elseif($orderStatus > 0) //已审核的订单
        {
            $db->where('a.company_check_status','>',0);
        }


        if($keywords != ''){
            $db->where(function($query) use ($keywords){
                $keywords = "%{$keywords}%";
                $query->orWhere('a.new_member_name','like',$keywords)
                    ->orWhere('a.new_member_mobile','like',$keywords)
                    ->orWhere('a.new_company_name','like',$keywords)
                    ->orWhere('a.new_company_code','like',$keywords);
            });
        }

        $orders = $db->orderBy('a.chapter_order_id','desc')->paginate(9);

        $memberTypes    = ['company'=>'企业','member'=>'个人','clo'=>'学习官'];
        foreach($orders as $order){
            $order->memberTypeName = $memberTypes[$order->order_type];
        }
        return $orders;
    }

    /**
     * 获取订单ID
     *
     * */
    public function get_order_info($orderId){


        $orderInfo = DB::table('chapter_order as a')
            ->leftJoin('chapter as b','b.chapter_id','=','a.chapter_id')
            ->select('a.*','b.chapter_name')
            ->where('a.chapter_order_id',$orderId)
            ->first();
        $memberTypes    = ['company'=>'企业','member'=>'个人','clo'=>'学习官'];
        $orderInfo->order_type_name = $memberTypes[$orderInfo->order_type];
        return $orderInfo;
    }


    /**
     * 获取订单的处理情况
     * @param integar $chapterOrderId 报单ID
     * @param integar $userId 用户ID
     * @return object
     * */
    public function get_order_check_info($chapterOrderId,$userId){

        $chapterOrderLogInfo = DB::table('chapter_order_log')
            ->where('chapter_order_id',$chapterOrderId)
            ->where('user_id',$userId)
            ->where('is_delete',0)
            ->orderBy('chapter_order_log_id','desc')
            ->first();
        return $chapterOrderLogInfo ? $chapterOrderLogInfo : false ;
    }




    /**
     * 修改分会订单
     * @param $orderId integar 订单ID
     * @param $info array 要修改的信息
     * */
    public function update_chapter_order( $orderId,array $info){
        $result = DB::table('chapter_order')
            ->where('chapter_order_id',$orderId)
            ->update($info);
        return $result;

    }

}

